//
// Created by hjie on 23-6-3.
//

#include "write_buffer.h"

WriteBuffer::WriteBuffer(int buffer_size)
{
    m_data_length = 0;
    m_buffer.resize(buffer_size);
}

WriteBuffer::~WriteBuffer()
{
    m_buffer.clear();
    m_buffer.shrink_to_fit();
}

uint8_t *WriteBuffer::Data()
{
    return &(*m_buffer.begin());
}

size_t WriteBuffer::Length()
{
    return m_data_length;
}

void WriteBuffer::RemoveSize(int size)
{
    if (size > m_data_length)
    {
        Clear();
    }
    else
    {
        m_data_length -= m_data_length;
        std::fill(m_buffer.begin(), m_buffer.begin() + size, 0);
    }
}

void WriteBuffer::Clear()
{
    m_data_length = 0;
    std::fill(m_buffer.begin(), m_buffer.end(), 0);
}

void WriteBuffer::Write(const uint8_t *data, int length)
{
    if (m_buffer.size() - m_data_length >= length)
    {
        memcpy(&(*(m_buffer.begin() + m_data_length)), data, length);
        m_data_length += length;
    }
    else
    {
        m_buffer.resize(m_buffer.size() + length * 2);
        memcpy(&(*(m_buffer.begin() + m_data_length)), data, length);
        m_data_length += length;
    }
}

void WriteBuffer::Write(uint8_t data)
{
    Write(&data, sizeof(uint8_t));
}

void WriteBuffer::Write(uint16_t data)
{
    Write((uint8_t*)&data, sizeof(uint16_t));
}

void WriteBuffer::Write(uint32_t data)
{
    Write((uint8_t*)&data, sizeof(uint32_t));
}

void WriteBuffer::Write(uint64_t data)
{
    Write((uint8_t*)&data, sizeof(uint64_t));
}


